package com.atguigu.tingshu.payment.listener;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.common.constant.RabbitConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Map;

@Component
@Slf4j
public class PaymentMqListener {
    @Autowired
    PaymentInfoService paymentInfoService;
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = RabbitConstant.PAYMENT_CLOSE_QUEUE , durable = "true"),
                    exchange = @Exchange(value = RabbitConstant.PAYMENT_EXCHANGE , type = "topic"),
                    key = {RabbitConstant.PAYMENT_CLOSE_RK}
            )
    })
    @SneakyThrows
    public void closePaymentInfo(Channel channel , Message message ,
                                  String orderNo){
        //关闭微信交易记录
        try {
            if(!StringUtils.isEmpty(orderNo)){
                paymentInfoService.update(Wrappers.lambdaUpdate(PaymentInfo.class)
                        .eq(PaymentInfo::getOrderNo , orderNo)
                        .eq(PaymentInfo::getPaymentStatus , SystemConstant.PAYMENT_STATUS_UNPAID)
                        .set(PaymentInfo::getPaymentStatus , SystemConstant.PAYMENT_STATUS_CLOSE));
            }

            channel.basicAck(message.getMessageProperties().getDeliveryTag() , false);
        } catch (Exception e) {
            if(message.getMessageProperties().isRedelivered()){
                log.error("交易日志状态更新失败，消息内容：{}" , orderNo);
                channel.basicReject(message.getMessageProperties().getDeliveryTag() , false);
            }else{
                log.warn("交易日志状态更新失败，尝试重试，消息内容：{}" , orderNo);
                channel.basicNack(message.getMessageProperties().getDeliveryTag() , false,true);
            }
        }


    }
}
